﻿using System.Collections.ObjectModel;
using DynamicData;

namespace Everywhere.Extensions;

public static class DynamicDataExtension
{

    /// <summary>
    /// A convenience method to add the disposable to a collection.
    /// </summary>
    /// <param name="disposable"></param>
    /// <param name="disposables"></param>
    public static void AddTo(this IDisposable disposable, ICollection<IDisposable> disposables) => disposables.Add(disposable);

    /// <param name="source"></param>
    /// <typeparam name="T"></typeparam>
    extension<T>(IObservable<IChangeSet<T>> source) where T : notnull
    {
        /// <summary>
        /// A convenience method to revert the out parameter pattern of Bind method.
        /// </summary>
        /// <param name="disposable"></param>
        /// <param name="resetThreshold"></param>
        /// <returns></returns>
        public ReadOnlyObservableCollection<T> BindEx(
            out IDisposable disposable,
            int resetThreshold = 25)
        {
            disposable = source.Bind(out var collection, resetThreshold).Subscribe();
            return collection;
        }

        /// <summary>
        /// A convenience method to add the subscription disposable to a collection.
        /// </summary>
        /// <param name="disposables"></param>
        /// <param name="resetThreshold"></param>
        /// <returns></returns>
        public ReadOnlyObservableCollection<T> BindEx(
            ICollection<IDisposable> disposables,
            int resetThreshold = 25)
        {
            var subscription = source.Bind(out var collection, resetThreshold).Subscribe();
            disposables.Add(subscription);
            return collection;
        }
    }
}